function Utils() {
};

Utils.clean_datepicker = function() {
  var old_fn = $.datepicker._updateDatepicker;
  $.datepicker._updateDatepicker = function(inst) {
    old_fn.call(this, inst);
    var buttonPane = $(this).datepicker("widget").find(".ui-datepicker-buttonpane");
    $("<button type='button' class='ui-datepicker-clean ui-state-default ui-priority-primary ui-corner-all'>Clear</button>").appendTo(buttonPane).click(function(ev) {
      $.datepicker._clearDate(inst.input);
    });
  }
};

Utils.get_array = function(objs, parent_id) {
  var result = [];
  for (var idx in objs) {
    var itm = objs[idx];
    itm.order = idx;
    itm.parent_id = parent_id;
    result.push(itm);
    if (itm.children && itm.children.length > 0) {
      result = result.concat(Utils.get_array(itm.children, itm.id));
      delete itm.children;
    }
  }
  return result;
};

Utils.get_short = function(str, len) {
  if (str.length <= len) {
    return str;
  }
  var left = str.substr(0, len);
  return left + '...';
};

Utils.unique = function(len) {
  len = len ? len : 16;
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for( var i=0; i < len; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

Utils.find_pos = function(elem) {
  var curleft = 0, curtop = 0;
  if (elem.offsetParent) {
    curleft = elem.offsetLeft;
    curtop = elem.offsetTop;
    while ((elem = elem.offsetParent)) {
      curleft += elem.offsetLeft;
      curtop += elem.offsetTop;
    }
  }
  return [ curleft, curtop ];
};

Utils.message = function(str, type) {
  window.scrollTo(0, 0);
  return $(".cs_header").noty( {
    text : str,
    type : type
  });
};

Utils.block_ui = function(opts) {
  $.blockUI({ message: '<div style="font-size: 12px; padding: 10px 0; font-weight: bold;">' + ((opts && opts.ld) ? opts.ld : '<img src="../3rd_party/blockUI/ajax-loader.gif" alt="Loading..."></img>') + '</div>' });
};

Utils.parse = function(str) {
  try {
    return JSON.parse(str);
  } catch (ex) {
    return '';
  }
};

Utils.clone = function(obj) {
  return JSON.parse(JSON.stringify(obj));
};

Utils.get_root = function(pages) {
  var root = {
    id : 0,
    parent_id : 0,
    name : '__Root__',
    order : 0,
    __c : []
  };
  Utils.__get_root(root, pages);
  return root;
};

Utils.__get_root = function(node, pages) {
  node.__c = [];
  for (var idx in pages) {
    var itm = pages[idx];
    if (itm.parent_id == node.id) {
      node.__c[node.__c.length] = itm;
      Utils.__get_root(itm, pages);
    }
  }
};

Utils.splice_by_id = function(id, arr) {
  for (var idx in arr) {
    var itm = arr[idx];
    if (itm.id == id) {
      arr.splice(idx, 1);
    }
  }
};

Utils.get_by_id = function(id, arr) {
  for (var idx in arr) {
    var itm = arr[idx];
    if (itm.id == id) {
      return itm;
    }
  }
  return null;
};

Utils.exist = function(elm, arr) {
  for (var idx in arr) {
    var itm = arr[idx];
    if (itm == elm) {
      return true;
    }
  }
  return false;
};

Utils.sort_by_attr = function(attr, arr) {
  arr.sort(function(a, b) {
    return a[attr].localeCompare(b[attr]);
  });
};

Utils.get_inst_cd = function(inst) {
  return '{' + inst.__folder + ':' + inst.id + '}';
};

Utils.plugin = function(ifm_id) {
  var ifm = document.getElementById(ifm_id);
  if (ifm && !window.opera){
    if (ifm.contentDocument && ifm.contentDocument.body){
      var body = ifm.contentDocument.body;
      var html = ifm.contentDocument.documentElement;
      ifm.style.height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) + 'px';
    } else if (ifm.document.body && ifm.document.documentElement) {
      var body = ifm.document.body;
      var html = ifm.document.documentElement;
      document.all(ifm_id).style.height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) + 'px';
    }
  }
};

Utils.leftbar = function(objs, id, title, attr, rt) {
  var html  = '<h3 style="padding-left: 10px;">' + title + '</h3>' +
              '<ul class="modern-menu mm-vertical"></ul>';
  if (parent != window) {
    parent.$("#cs_leftbar_objs").empty();
    parent.$("#cs_leftbar_objs").append(html);
  } else {
    $("#cs_leftbar_objs").empty();
    $("#cs_leftbar_objs").append(html);
  }

  for (var idx in objs.d) {
    var itm = objs.d[idx];
    html = '<li' + ((itm.id == id) ? ' class="modern-menu-hi"' : '') + '><a href="#" onclick="$(\'.ui-dialog\').remove(); return get_obj(\'' + itm.id + '\')"><span>' + Utils.get_short(itm[attr], 15) + '</span></a></li>';
    if (parent != window) {
      parent.$("#cs_leftbar_objs .modern-menu").append(html);
    } else {
      $("#cs_leftbar_objs .modern-menu").append(html);
    }
  }

  if (objs.d.length > 0) {
    if (parent != window) {
      setTimeout(function() { parent.$('#cs_leftbar_objs .modern-menu').modernMenu(); }, 50);
    } else {
      setTimeout(function() { $('#cs_leftbar_objs .modern-menu').modernMenu(); }, 50);
    }

    html  = '<div id="lb_pagination" class="pagination">' + 
              '<a href="#" class="first" data-action="first">&laquo;</a>' + 
              '<a href="#" class="previous" data-action="previous">&lsaquo;</a>' + 
              '<input type="text" readonly="readonly" />' + 
              '<a href="#" class="next" data-action="next">&rsaquo;</a>' + 
              '<a href="#" class="last" data-action="last">&raquo;</a>' + 
            '</div>';

    if (parent != window) {
      parent.$("#cs_leftbar_objs").append(html);
      parent.$('#lb_pagination').jqPagination({
        current_page: objs.p,
        max_page: Math.ceil(objs.t / objs.s),
        paged: function(page) {
          rt(page);
        }
      });
    } else {
      $("#cs_leftbar_objs").append(html);
      $('#lb_pagination').jqPagination({
        current_page: objs.p,
        max_page: Math.ceil(objs.t / objs.s),
        paged: function(page) {
          rt(page);
        }
      });
    }
  }
};

Utils.set_attrs = function(attrs, opts) {
  attrs = attrs.sort(function(a, b) {
    return parseInt(a.id, 10) > parseInt(b.id, 10) ? 1 : -1;
  });
  opts = opts.sort(function(a, b) {
    return parseInt(a.id, 10) > parseInt(b.id, 10) ? 1 : -1;
  });
  for (var idx in attrs) {
    var itm = attrs[idx];
    itm.__opts = [];
    for (var idx2 in opts) {
      var itm2 = opts[idx2];
      if (itm2.product_attr_id == itm.id) {
        itm.__opts.push(itm2);
      }
    }
  }
};

Utils.get_price = function(currs, from, to, price, discount) {
  var r1, r2;
  for (var idx in currs) {
    var itm = currs[idx];
    if (itm.title == to) {
      r1 = itm.rate;
    }
    if (itm.title == from) {
      r2 = itm.rate;
    }
  }
  price = price * (r1 / r2);
  if (discount) {
    price = price * ((100 - discount) / 100);
  }
  return price;
};

Utils.init_ecomm = function() {
  __curr = Cookie.get_cookie('curr');
  if (!__curr) {
    for (var idx in __currs) {
      var itm = __currs[idx];
      if (itm.is_default == 1) {
        __curr = itm;
        Cookie.set_cookie('curr', JSON.stringify(__curr), 1);
      }
    }
  } else {
    __curr = JSON.parse(__curr);
  }
  $('#curr_' + __curr.title).prop('checked', true);
  $('#currs').buttonset();
};

Utils.set_cartnum = function(cart) {
  var val = 0;
  for (var idx in cart) {
    var itm = cart[idx];
    val += parseFloat(itm.quantity, 10);
  }
  $('#cs_cart').html(val);
};

Utils.encodeURI= function(text) {
  text = text.replace(/\+/g, '%2B');
  return encodeURIComponent(text);
};

